//
//  BlurView.h
//  Copyright (c) 2016年 sewm. All rights reserved.
//
#import "BlurView.h"

@interface BlurView () {
    UIToolbar *_nativeBlurView;
}
@end

@implementation BlurView

- (void)dealloc {
    _nativeBlurView = nil;
}

#pragma mark - Init functions

// general initializer
- (id)init {
    self = [super init];
    if (self) {
        [self setupView];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setupView];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
    }
    return self;
}

- (void)setupView {
    [self setClipsToBounds:YES];
    self.backgroundColor = [UIColor clearColor];
    if (!_nativeBlurView) {
        _nativeBlurView = [[UIToolbar alloc] initWithFrame:[self bounds]];
        [self.layer insertSublayer:[_nativeBlurView layer] atIndex:0];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [_nativeBlurView setFrame:[self bounds]];
}

#pragma mark - Blur view functions

- (void)setBlurColor:(UIColor *)blurColor {
    [self setBackgroundColor:blurColor];
}

- (void)setBlurAlpha:(CGFloat)alphaValue {
    int numComponents = CGColorGetNumberOfComponents([[self backgroundColor] CGColor]);
    if (numComponents == 4) {
        const CGFloat *components = CGColorGetComponents([[self backgroundColor] CGColor]);
        CGFloat red = components[0];
        CGFloat green = components[1];
        CGFloat blue = components[2];
        [self setBackgroundColor:[UIColor colorWithRed:red green:green blue:blue alpha:alphaValue]];
    } else {
        if (_nativeBlurView.barStyle == UIBarStyleBlackTranslucent) {
            [self setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:alphaValue]];
        } else {
            [self setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:alphaValue]];
        }
    }
}

- (void)setBlackStyle:(BOOL)blackStyle {
    _nativeBlurView.barStyle = blackStyle ? UIBarStyleBlackTranslucent : UIBarStyleDefault;
}
@end
